<template>
  <!-- 个人注册 -->
  <div class="register-wrap">
    <div v-show="!visible" class="form-background">
      <div class="title-container">
        <el-image class="logo" :src="logo" fit="fill" />
        <p class="title">个人注册</p>
      </div>
      <div class="register-form">
        <!-- 注册信息 -->
        <el-form
          ref="loginRef"
          label-position="top"
          :model="loginData"
          :rules="loginRules"
        >
          <el-form-item prop="phone">
            <el-input v-model="loginData.phone" tabindex="1" placeholder="请输入手机号">
              <i slot="prefix" class="iconfont icon-qiyeshenfenrz" />
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              ref="password"
              v-model="loginData.password"
              :type="passwordType"
              name="password"
              tabindex="2"
              autocomplete="on"
              placeholder="密码（由数字加字母且大于6位）"
            >
              <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
            </el-input>
            <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
          <el-form-item prop="passwords">
            <el-input ref="password" v-model="loginData.passwords" :type="passwordType" placeholder="确认密码">
              <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
            </el-input>
            <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
          <el-form-item prop="code">
            <el-input
              v-model="loginData.code"
              auto-complete="off"
              placeholder="验证码"
              style="width: 63%"
            >
              <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
              <i slot="suffix" class="el-icon-refresh" style="cursor:pointer;" @click="getCode" />
            </el-input>
            <div class="login-code">
              <img v-if="showCode" :src="codeUrl" @click="getCode">
              <svg-icon
                v-if="!showCode"
                icon-class="pic-broken"
                style="cursor:pointer;width: 100px;height: 40px;"
                @click="getCode"
              />
            </div>
          </el-form-item>
          <button class="reg-btn" @click.prevent="handleRegister">下一步</button>
          <p class="login">
            <span @click="toEnterprise">企业注册</span>
            <span>已有账号？</span>
            <span @click="toLogin">去登录</span>
          </p>
        </el-form>
      </div>
    </div>
    <section v-show="visible" class="enterprise-info">
      <div v-loading="loading" class="dialog">
        <h3>完善个人资料</h3>
        <div class="form-person">
          <el-form ref="formRef" :model="formData" :rules="rules" label-width="110px">
            <el-row :gutter="10">
              <el-col :span="8">
                <!-- idCardFile 马德旺说让换的-->
                <el-form-item label="身份证附件" prop="idCardFile" style="margin-bottom: 0">
                  <ImgUploadIdCard
                    ref="fileUplode"
                    @getIDCardData="getIDCardData"
                    @getFilePic="getIdCardFilePic"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="name" label="用户名称">
                  <el-input v-model="formData.name" placeholder="请输入用户名称" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="idCard" label="身份证号">
                  <el-input v-model="formData.idCard" placeholder="请输入身份证号" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="email" label="邮箱">
                  <label slot="label" v-html="`邮&emsp;&emsp;箱`" />
                  <el-input v-model="formData.email" placeholder="请输入邮箱" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="sex" label="">
                  <label slot="label" v-html="`性&emsp;&emsp;别`" />
                  <el-select v-model="formData.sex" style="width:100%" clearable placeholder="请选择性别">
                    <el-option
                      v-for="item in sexOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="surveyType" label="人员类型">
                  <el-select v-model="formData.surveyType" style="width:100%" clearable placeholder="请选择人员类型" @change="checkUserType">
                    <el-option
                      v-for="item in userTypeOption"
                      :key="item.typeNum"
                      :label="item.typeName"
                      :value="item.typeNum"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="" prop="province">
                  <template slot="label">
                    <span class="labelTitle">所在区域</span>
                  </template>
                  <el-cascader v-model="formData.currentProvince" placeholder="请选择所在区域" :props="cityNormalizer" :options="cityOptions" clearable style="width: 100%" @change="changeCitySelect">
                    <template slot-scope="{ data }">
                      <span>{{ data.label }}</span>
                    </template>
                  </el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="" prop="isCheck">
                  <template slot="label">
                    <span class="labelTitle">审核方式</span>
                  </template>
                  <el-select v-model="formData.isCheck" style="width:100%" clearable placeholder="请选择审核方式">
                    <el-option
                      v-for="item in isCheckList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-form :inline="true" label-width="110px">
            <el-row :gutter="10">
              <el-col v-for="cert in userCertificates" :key="cert.id" :span="12" class="certificate-wrap">
                <div class="certi-item">
                  <h3 class="certi-titile">{{ cert.certificateName }}</h3>
                  <el-row>
                    <el-col :span="8">
                      <div class="upload">
                        <ImgUploadOneC
                          :cert-id="certId"
                          :edit-file-list="cert.appFiles"
                          @getCertData="getCertData"
                          @click.native="handleId(cert.id)"
                          @getFilePic="cert.appFilePic = $event"
                        />
                      </div>
                    </el-col>
                    <el-col :span="16">
                      <el-form-item v-for="item in cert.detailList" :key="item.id" :label="item.fieldName" prop="">
                        <el-input v-model="item.value" placeholder="" size="small" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </div>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="btn-wrap">
          <el-button size="medium" type="primary" @click="visible = false">上一步</el-button>
          <el-button size="medium" type="primary" @click="goRegister">注册</el-button>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
/** 页面组件 start*/
import ImgUploadOneC from '@/components/Upload/ImgUploadOneC'
import ImgUploadIdCard from '@/components/Upload/ImgUploadIdCard'
import logo from '@/assets/image/logo.png'
import { validatePhone, validateIdNo } from '@/utils/validate'
import { personTypeListNoPermission } from '@/api/superviseBaseInfo/typeManage/personnelType/index'
/** 页面组件 end*/

/** 页面接口 start*/
import { listRegionTree } from '@/api/common/area.js'
import { changeCertificate, checkUserIphone, personnelRegister } from '@/api/register'
import { captchaImage } from '@/api/user' // 验证码接口
/** 页面接口 end*/
import { validateNumLetter, validEmail, validEmail01 } from '@/utils/validate.js'
export default {
  components: {
    ImgUploadIdCard,
    ImgUploadOneC
  },
  data() {
    const passwordLength = (rule, value, callback) => {
      if (value.length < 6 || value.length > 20) {
        return callback(new Error('登录密码不能少于6位且不能大于20位'))
      } else {
        callback()
      }
    }
    const validPassword = (rule, value, callback) => {
      if (this.loginData.password !== value) {
        callback(new Error('请确认密码输入是否一致'))
      } else {
        callback()
      }
    }
    const checkIphone = (rule, value, callback) => {
      if (!value) return
      checkUserIphone(value).then(res => {
        res.code === 200 && callback()
      })
    }
    return {
      loading: false,
      certId: '',
      logo: logo, // logo图片地址
      codeUrl: '', // 验证码
      showCode: false, // 验证码正常显示
      userTypeOption: [], // 用户类型
      passwordType: 'password', // 密码图标
      sexOptions: [
        { value: '0', label: '男' },
        { value: '1', label: '女' }
      ], // 性别数组
      // 审核方式
      isCheckList: [
        { value: '0', label: '手动审核' },
        { value: '1', label: '自动审核' }
      ],
      // 账号密码
      loginData: {
        phone: '', // 登录账号
        password: '', // 密码
        passwords: '', // 确认密码
        code: '' // 验证码
      },
      // 个人注册表单
      formData: {
        name: '', // 用户名称
        email: '', // 邮箱
        idCard: '', // 身份证号
        surveyType: '', // 人员类型
        sex: '1',
        phone: '',
        currentProvince: '',
        province: '', // 省
        city: '', // 市
        county: '', // 县
        isCheck: '1', // 审核
        idCardFile: '' // 身份证附件
      },
      // 选择的城市
      currentProvince: '',
      cityOptions: [], // 城市数据
      cityNormalizer: {
        value: 'value',
        label: 'label',
        children: 'children'
      },
      // 账号密码规则
      loginRules: {
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { required: true, validator: validatePhone, trigger: 'blur' },
          { required: true, validator: checkIphone, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { required: true, validator: passwordLength, trigger: 'blur' },
          { required: true, validator: validateNumLetter }
        ],
        passwords: [
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          { required: true, validator: validPassword, trigger: 'blur' }
        ],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      },
      // 个人注册规则
      rules: {
        name: [
          { required: true, message: '请输入用户名称', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { required: true, validator: validEmail, message: '请输入正确的邮箱' },
          { validator: validEmail01, message: '请输入QQ或163或126邮箱' }
        ],
        idCard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { required: true, validator: validateIdNo, trigger: 'blur' }
        ],
        idCardFile: [{ required: true, message: '身份证附件不能为空', trigger: 'blur' }],
        surveyType: [
          { required: true, message: '请选择人员类型', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'blur' }
        ],
        province: [
          { required: true, message: '所在区域不得为空' }
        ],
        isCheck: [
          { required: true, message: '请选择审核方式' }
        ]
      },
      visible: false, // 弹出信息
      userCertificates: [] // 证书数据

    }
  },
  mounted() {
    // 图片验证码
    this.getCode()
    this.getRegionTree()
  },
  methods: {
    getCertData(data, certId) {
      const cert = this.userCertificates.find(item => item.id === certId)
      if (!cert) return
      cert.detailList.forEach(item => {
        this.$set(item, 'value', '')
      })
      for (const k in data) {
        const item = cert.detailList.find(item => item.fileVal === k)
        if (item) {
          this.$set(item, 'value', data[k])
        }
      }
    },
    handleId(certId) {
      this.certId = certId
    },
    // 身份证附件
    getIdCardFilePic(fileList) {
      this.formData.idCardFile = fileList[0].fileId
    },
    // 获取身份证信息
    getIDCardData(IDCardData) {
      console.log(IDCardData)
      if (!IDCardData || !IDCardData.姓名 || !IDCardData.公民身份号码 || !IDCardData.性别) return
      this.formData.name = IDCardData.姓名.words
      this.formData.idCard = IDCardData.公民身份号码.words
      this.formData.sex = IDCardData.性别.words === '女' ? '1' : '0'
    },
    // 是否显示密码
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
    },
    async checkUserType(typeNum) {
      const { data } = await changeCertificate({ typeFlag: '0', typeNum })
      if (data) {
        data.sort((a, b) => {
          a.detailList.sort((c, d) => c.orderNum - d.orderNum)
          return a.orderNum - b.orderNum
        })
        this.userCertificates = data
      }
    },
    // 图片验证
    getCode() {
      captchaImage()
        .then((res) => {
          this.codeUrl = 'data:image/gif;base64,' + res.data.img
          this.formData.uuid = res.data.uuid
          this.showCode = true
        })
        .catch(() => {
          this.showCode = false
        })
    },
    // 注册账号
    handleRegister() {
      this.$refs.loginRef.validate((valid) => {
        if (valid) {
          this.visible = true
          this.getSupperType()
        }
      })
    },
    // 获取区域树
    async getRegionTree() {
      const { data } = await listRegionTree({ regionCode: '' })
      if (data) {
        this.cityOptions = data
      }
    },
    // 所属区域
    changeCitySelect(regionCode) {
      const [province, city, county] = regionCode
      this.formData.province = province // 省
      this.formData.city = city// 市
      this.formData.county = county // 区/县
    },
    // 提交注册信息
    goRegister() {
      this.$refs.formRef.validate(async(valid) => {
        if (valid) {
          this.loading = true
          const { formData, userCertificates, loginData } = this
          const flag = userCertificates.some(item => {
            // 证书附件值
            if (item.appFilePic === undefined) return true
            // 字段值
            return item.detailList.some(val => val.value === undefined || val.value.trim() === '')
          })
          if (flag) {
            this.msgWarning('证书附件和信息不能为空!')
            this.loading = false
            return
          }
          const certList = userCertificates.map(cert => {
            const { id, appFilePic, detailList, certificateName } = cert
            const certificateVal = detailList.map(item => {
              const { fieldName, fileVal, value, isRemind } = item
              return { fieldName, fileVal, value, isRemind }
            })
            return { certificateName, certificateId: id, fileId: appFilePic[0].fileId, certificateVal: JSON.stringify(certificateVal) }
          })
          try {
            const { code } = await personnelRegister({ ...formData, ...loginData, userCertificates: certList })
            if (code === 200) {
              this.msgSuccess('注册成功')
              this.$router.push('/login')
            }
          } catch {
            this.loading = false
          }
        }
      })
    },
    // 获取人员类型
    async getSupperType() {
      const { data: { rows }} = await personTypeListNoPermission()
      this.userTypeOption = rows
    },
    // 已经账号去登录
    toLogin() {
      this.$router.push('/login')
    },
    // 跳转企业注册页面
    toEnterprise() {
      this.$router.push('/EnterpriseRegister')
    }
  }
}
</script>
